package tech.summerly.weather.component.adapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.item_camera_description.view.*
import tech.summerly.weather.R
import tech.summerly.weather.model.LiveWeatherSource
import tech.summerly.weather.util.ViewHolder

/**
 * the [RecyclerView.Adapter] for LiveWeatherFragment's cameras list
 */
class CameraDescriptionAdapter(
        val cameras: List<LiveWeatherSource>,
        val onItemClickListener: (view: View, position: Int) -> Unit
) : RecyclerView.Adapter<ViewHolder>() {


    private var currentSelectedCamera: String? = null

    private fun updateSelection(id: String) {
        val i = cameras.indexOfFirst { it.id == id }
        if (i != -1) {
            notifyItemChanged(i)
        }
    }

    fun setSelected(id: String) {
        val old = currentSelectedCamera
        currentSelectedCamera = id
        old?.let(this::updateSelection)
        updateSelection(id)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(R.layout.item_camera_description, parent, LayoutInflater.from(parent.context))
    }

    override fun getItemCount(): Int {
        return cameras.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int): Unit = with(holder.itemView) {
        val source = cameras[position]
        viewIndicator.isVisible = source.id == currentSelectedCamera
        textTitle.text = source.name
        setOnClickListener {
            onItemClickListener(it, position)
        }
    }

}